
import { List, Checkbox } from 'antd-mobile';
import React from 'react';
import style from './style.module.scss';
import CommodityListItem from 'components/CommodityListItem'
import { decorator } from 'grey-react-box';
import { RouteChildrenProps, withRouter } from 'react-router-dom';
import { useUrlParameter, setUrlParameter } from 'router/utils';
import { server } from 'server';
import lazy from 'router/utils/lazy';

const SettleAccounts = lazy(() => import('page/SettleAccounts'));

export default decorator<any, RouteChildrenProps>(withRouter)(props => {

    const [sa] = useUrlParameter('sa');

    const { updateGoodsList, goodsList, addGoods, removeGoods, selectedGoods, selecte, selecteAll, delGoods } = useShoppingCart();

    const total = React.useMemo(() => {
        let sum = 0;
        selectedGoods.map(e => goodsList.filter(t => t.id === e)[0]).forEach(e => {
            if (e) {
                sum += parseInt(e.goodsPrice) * parseInt(e.goodsNum)
            }
        })
        return sum;
    }, [selectedGoods, goodsList])

    const onSettlement = React.useCallback(async () => {
        console.log(selectedGoods, goodsList);
        const par: any[] = [];
        selectedGoods.forEach(e => {
            const g = goodsList.filter(t => t.id === e)[0];
            if (g) {
                par.push({
                    id: g.id, 
                    goodsNumber: parseInt(g.goodsNum)
                })
            }
        })
        const ajax = await server.post('/medicine/order/createOrder', par).end();
        if (ajax.err) {
        } else {
            setUrlParameter({ sa: ajax.res.body.data });
            delGoods();
        }
    }, [selectedGoods, goodsList, delGoods])

    React.useEffect(() => {
        updateGoodsList();
    }, [updateGoodsList])

    return (
        <>
            <div className={style.body} style={{ display: sa && 'none' }} >
                <List className={style.list} >
                    {goodsList.map((e, i) => {
                        return (
                            <div key={i} className={style.item} >
                                <Checkbox className={style.checkbox} onChange={() => { selecte(e.id) }} checked={selectedGoods.indexOf(e.id) >= 0} />
                                <CommodityListItem
                                    style={{ flex: 1 }}
                                    img={e.imageUrl}
                                    price={e.goodsPrice}
                                    title={e.goodsName}
                                />
                                <div className={style.edit} >
                                    <div className={style.add} onClick={() => { addGoods(e.id) }} >+</div>
                                    <div className={style.num} >{e.goodsNum}</div>
                                    <div className={style.sho} onClick={() => { removeGoods(e.id) }} >-</div>
                                </div>
                            </div>
                        )
                    })}
                </List>
                <div className={style.foot} >
                    <div className={style.total} >总价:¥{total}</div>
                    <div className={style.del} onClick={delGoods} >删 除</div>
                    <div className={style.cart} onClick={selecteAll} >全 选</div>
                    <div className={style.buy} onClick={onSettlement} >结 算</div>
                </div>
            </div>
            {sa && <SettleAccounts />}
        </>
    )
})

const useShoppingCart = () => {

    const [goodsList, setGoodsList] = React.useState<any[]>([]);

    const [selectedGoods, setSelectedGoods] = React.useState<any[]>([])

    /** 选择了一个商品 */
    const selecte = React.useCallback(id => {
        if (selectedGoods.indexOf(id) < 0) {
            setSelectedGoods([...selectedGoods, id]);
        } else {
            setSelectedGoods(selectedGoods.filter(e => e !== id));
        }
    }, [selectedGoods])

    /** 全部选中 */
    const selecteAll = React.useCallback(() => {
        setSelectedGoods(goodsList.map(e => e.id));
    }, [goodsList])

    /** 从服务器更新 */
    const updateGoodsList = React.useCallback(async () => {
        const ajax = await server.post('/medicine/shopping/query', {}).end();
        if (ajax.err) {

        } else {
            setGoodsList(ajax.res.body.data);
        }
    }, [])

    /** 添加产品 */
    const addGoods = React.useCallback(async cid => {
        const ajax = await server.post('/medicine/shopping/add', { goodsId: cid, number: 1 }).end();
        if (ajax.err) {

        } else {
            updateGoodsList();
        }
    }, [updateGoodsList])

    /** 移除商品 */
    const removeGoods = React.useCallback(async cid => {
        const ajax = await server.post('/medicine/shopping/remove', { goodsId: cid, number: 1 }).end();
        if (ajax.err) {

        } else {
            updateGoodsList();
        }
    }, [updateGoodsList])

    /** 删除选中的商品 */
    const delGoods = React.useCallback(async () => {
        for (let i = 0; i < selectedGoods.length; i++) {
            const goodsId = selectedGoods[i];
            const number = goodsList.filter(e => e.id === goodsId)[0]?.goodsNum;

            if (goodsId && number) {
                await server.post('/medicine/shopping/remove', { goodsId, number }).end();
            }
        }

        updateGoodsList();
    }, [selectedGoods, goodsList, updateGoodsList])

    return {
        selecte,
        selectedGoods,
        goodsList,
        selecteAll,
        addGoods,
        removeGoods,
        updateGoodsList,
        delGoods,
    }
}